#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id$"

# Import system modules

# Import third-party module
from django.core.exceptions import ObjectDoesNotExist

# Import local modules
from docket import models
from docket.vtr import parse_stream

# Module

class ErrorKeeper(object):
    def __init__(self):
        self.errors = []
    def __call__(self, startLine, endLine, lines, err):
        self.errors.append( {'start':startLine,
                             'end':endLine,
                             'lines':lines,
                             'error':err,
                             } )

def load_data_from_stream(input, store=True, verbose=False, message_stream=None, errorcb=None):
    """Given a stream of text data, parse it for VTR data and load the results into the db."""
    num_existing = 0
    num_new = 0
    
    for record in parse_stream(input, verbose=verbose, errorcb=errorcb):
        print >>message_stream, str(record)
        
        try:
            existing = models.Case.objects.get(year=record.year,
                                                num=record.case)
            print >>message_stream, 'Found existing case:', existing
            num_existing += 1
        except ObjectDoesNotExist:
            num_new += 1
            try:
                year, volume = record.book.split('/')
                book = models.Book.objects.get(year=year, volume=volume)
            except ObjectDoesNotExist:
                book = models.Book(year=year, volume=volume)
                print >>message_stream, 'New book:', book
                book.save()
            hearing_date = None
            if record.hearing_date is not None:
                hearing_date = record.hearing_date.date
            arrest_date = None
            if record.arrest_date is not None:
                arrest_date = record.arrest_date.date
            new_case = models.Case(year=record.year,
                                   num=record.case,
                                   book=book,
                                   page=int(record.book_page),
                                   arrest_date=arrest_date,
                                   arrest_location=record.location,
                                   hearing_date=hearing_date,
                                   plea=record.plea,
                                   outcome=record.outcome.upper(),
                                   notes=record.notes,
                                   )
            if store:
                new_case.save()
            
            for violation in record.violations:
                try:
                    vcode = models.ViolationCode.objects.get(code=violation.code)
                except ObjectDoesNotExist:
                    vcode = models.ViolationCode(code=violation.code)
                    print >>message_stream, 'New violation code:', vcode
                    vcode.save()
                    
                v = models.Violation(case=new_case, code=vcode, notes=violation.note)
                if store:
                    v.save()
                
            for participant in record.participants:
                role = models.Role.objects.get(name=participant.role)
                p = models.Participant(case=new_case, 
                                       role=role,
                                       first_name=participant.first,
                                       middle_name=participant.middle,
                                       last_name=participant.last,
                                       #license_plate=,
                                       alias=participant.alias,
                                       title=participant.title,
                                       suffix=participant.suffix,
                                       race=participant.race.upper(),
                                       gender=participant.gender.upper(),
                                       )
                if store:
                    p.save()
                
            for sentence in record.sentences:
                if sentence.date:
                    sentence_date = sentence.date.date
                else:
                    sentence_date = None
                s = models.Sentence(case=new_case,
                                    kind=sentence.kind,
                                    amount=sentence.amount,
                                    amount_kind=sentence.code,
                                    date=sentence_date,
                                    note=sentence.note,
                                    )
                if store:
                    s.save()
        
        print >>message_stream
    return (num_existing, num_new)
